package com.eascs.workflow.email.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.service.ILoanInfoService;
import com.eascs.admin.common.vo.LoanApplyEntity;
import com.eascs.admin.common.vo.LoanUserInfo;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.app.runtime.RuntimeSetting;
import com.eascs.common.util.DigestUtils;
import com.eascs.common.util.UuidUtil;
import com.eascs.notify.sms.SmsNotifier;
import com.eascs.notify.sms.SmsNotifyRequest;
import com.eascs.notify.sms.SmsSendType;
import com.eascs.web.sso.User;
import com.eascs.workflow.common.entity.sys.SysMessage;
import com.eascs.workflow.common.entity.wf.ProcessTaskMain;
import com.eascs.workflow.common.entity.wf.ProcessTaskNode;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.entity.wf.TaskNodeAuditor;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.email.dao.SysSendEmailOrMessageDao;
import com.eascs.workflow.email.service.WFSmsService;
import com.eascs.workflow.sys.dao.SysUserDao;

@Service
public class WFSmsServiceImpl implements WFSmsService {
	private static Logger log = LoggerFactory.getLogger(WFEmailServiceImpl.class);

	/** 加签 */
	public static final String SMS_TO_SIGN = "sign";

	/** 加签通过 */
	public static final String SMS_TO_SIGN_PASS = "signPass";
	/** 作废*/
	public static final String SMS_TO_CANCLE = "cancle";

	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysSendEmailOrMessageDao dao;
	@Reference
	private ILoanInfoService  loanInfoService;
	@Reference
	private SmsNotifier smsNotifier;

	@Override
	public void notifySMSToOperator(ProcessTaskMain taskMain, List<String> toList) {
		List<TaskNodeAuditor> auditorsList = new ArrayList<>();
		for (String auditorNo : toList) {
			TaskNodeAuditor auditor=new TaskNodeAuditor();
			auditor.setAuditorNo(auditorNo);
			auditorsList.add(auditor);
		}
		notifyEmail(taskMain, auditorsList, null, null, null);
	}

	@Override
	public void notifySMSToMainSign(ProcessTaskMain taskMain, List<TaskNodeAuditor> toList, String mailToType,
			User loginUser, TaskNodeAuditor nodeAuditor,ProcessTaskNode taskNode) {
		if(taskNode.getIsSendSms()!= null && taskNode.getIsSendSms() == 0)
		{
			log.info("节点配置不发送短信");
			return;
		}
		notifyEmail(taskMain, toList, mailToType, loginUser, nodeAuditor);
	}

	private void notifyEmail(ProcessTaskMain taskMain, List<TaskNodeAuditor> unDoList, String mailToType,
			User loginUser, TaskNodeAuditor nodeAuditor) {
		try {
			RuntimeSetting runtimeSetting = RuntimeSetting.get();
			//短信提醒的节点为：征信审查完成（含通过和驳回）后、内部审批完成（含通过和驳回）后，短信提醒经办信贷人员； 流程中如有加签，则通知被加签人。加签通过后通知加签人
			if (!StringUtils.equals(taskMain.getProcessType(), ProcessTemplate.PROECESS_TYPE_CREDIT)
					&& !StringUtils.equals(taskMain.getProcessType(), ProcessTemplate.PROECESS_TYPE_INAUDIT) 
					&& taskMain.getProcessStatus() != ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN
					&& taskMain.getProcessStatus() != ProcessTaskMain.PROECESS_STATUS_CLOSE) {
				return;
			}

			// 查找发送人的信息
			List<SmsNotifyRequest> mailEntryList = getToSMSList(taskMain.getTaskCode(),unDoList);
			if (mailEntryList != null && !mailEntryList.isEmpty()) {
				for (SmsNotifyRequest smsNotifyRequest : mailEntryList) {
					String content = null;
					String appliedDate = DateFormatUtils.format(taskMain.getAppliedDate(), "yyyy-MM-dd HH:mm");
					String processNo = taskMain.getReferCode();
					//客户姓名获取
					String loanName = "";
					String referId=taskMain.getReferId();
					if (StringUtils.isNotBlank(referId)) {
						com.eascs.admin.common.vo.ModelResult<LoanApplyEntity>  modelResult=loanInfoService.getLoanapplyInfo(referId);
						LoanApplyEntity loanApplyEntity=modelResult.getModel();
						LoanUserInfo loanUserInfo=loanApplyEntity.getLoanUserInfo();
						loanName=loanUserInfo.getCustomerName();
					}
					//获取短信内容
					if (StringUtils.equals(mailToType, SMS_TO_SIGN)) {
						content = "有新提交的[贷款审批]由 " + loginUser.getCname() + " ( " +  smsNotifyRequest.getRecipientNumber() + " ) 加签给您审批。单号：" + processNo + "，申请日期：" + appliedDate;
					} else if (StringUtils.equals(mailToType, SMS_TO_SIGN_PASS)) {
						String auditorName = nodeAuditor.getAuditorName();
						String auditorDate = DateFormatUtils.format(nodeAuditor.getAuditorDate(), "yyyy-MM-dd HH:mm");
						content = "您加签的[贷款审批]已审批完成。审批人：" + auditorName + "，单号：" + processNo + "，客户姓名：" + loanName + "，审核时间：" + auditorDate;
					} else {
						if (taskMain.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_PASS) {
							content = "您于" + appliedDate + "提交的[" + taskMain.getProcessType() + "]已经审核通过。单号：" + processNo + "，客户姓名：" + loanName;
						} else if (taskMain.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_TURNED_DOWN) {
							content = "您于" + appliedDate + "提交的[" + taskMain.getProcessType() + "]被驳回。单号：" + processNo;
						}else if (taskMain.getProcessStatus() == ProcessTaskMain.PROECESS_STATUS_CLOSE) {
							content = "您于" + appliedDate + "提交的[" + taskMain.getProcessType() + "]被否决。单号：" + processNo;
						}
					}
					if (StringUtils.isNotBlank(content)) {
						smsNotifyRequest.setContent(content);
						smsNotifyRequest.setRequestDateTime(new Date());
						smsNotifyRequest.setSmsSendType(SmsSendType.INSTANT);
//						message.setContent(content);
//						message.setCreateTime(new Date());
//						message.setSendType(SysMessage.SEND_TYPE_IMMEDIATELY);
//						message.setStatus(0);
						if (!runtimeSetting.getEnv().equals("prod")) { // 非生产环境
//							message.setStatus(1);
							smsNotifyRequest.setSmsSendType(SmsSendType.TEST);
						}
//						dao.insertMessage(message);
						log.info("referCode:[{}],taskCode:[{}],messageObj:[{}], 开始发送短信", taskMain.getReferCode(), taskMain.getTaskCode());
						smsNotifier.notify(smsNotifyRequest);
						log.info("referCode:[{}],taskCode:[{}],messageObj:[{}],短信发送入库成功", taskMain.getReferCode(), taskMain.getTaskCode(), smsNotifyRequest.toString());
					}
				}
			}
		} catch (Exception e) {
			log.error("referCode:[" + taskMain.getReferCode() + "],短信发送入库失败,errorMsg:[{}]", e.getMessage());
		}
	}

	/**
	 * 获取短信列表
	 * 
	 * @param unDoList
	 */
	/*private List<SysMessage> getToSMSList(List<TaskNodeAuditor> unDoList) {
		List<SysMessage> entryList = new ArrayList<SysMessage>();
		for (TaskNodeAuditor auditor : unDoList) {
			SysMessage entry = new SysMessage();
			User user = sysUserDao.getSysUserById(auditor.getAuditorNo());
			String mobile=user.getMobile();
			if (StringUtils.isNotBlank(mobile)) {
				mobile=user.getMobile().replace("+", "");
			}
			entry.setReceiveName(user.getCname());
			entry.setSendName("administrator");
			entry.setReceiveTelphone(mobile);
			
			entryList.add(entry);
		}
		return entryList;
	}*/
	
	/**
	 * 获取短信列表
	 * 
	 * @param unDoList
	 */
	private List<SmsNotifyRequest> getToSMSList(String taskCode,List<TaskNodeAuditor> unDoList) {
		List<SmsNotifyRequest> entryList = new ArrayList<SmsNotifyRequest>();
		for (TaskNodeAuditor auditor : unDoList) {
//			SysMessage entry = new SysMessage();
			SmsNotifyRequest paramSmsNotifyRequest=new SmsNotifyRequest();
			User user = sysUserDao.getSysUserById(auditor.getAuditorNo());
			String mobile=user.getMobile();
			if (StringUtils.isNotBlank(mobile)) {
				mobile=user.getMobile().replace("+", "");
			}
			paramSmsNotifyRequest.setSystemCode("工作流系统");
			paramSmsNotifyRequest.setRecipientNumber(mobile);
			paramSmsNotifyRequest.setReceiveName(user.getCname());
			paramSmsNotifyRequest.setSendName("administrator");
			paramSmsNotifyRequest.setBizCode(taskCode);
			paramSmsNotifyRequest.setRequestId(DigestUtils.md5With16(UuidUtil.generateFullUuid()));
//			entry.setReceiveName(user.getCname());
//			entry.setSendName("administrator");
//			entry.setReceiveTelphone(mobile);
			
			entryList.add(paramSmsNotifyRequest);
		}
		return entryList;
	}

}
